import LangTypeEnum from '@/framework/constant/LangTypeEnum'

export default class LangText {

  /**
   * @param col 列定义
   * @param lang 顶层lang配置
   * @returns {LangText}
   */
  static create(col = {}, lang = null) {
    return new LangText(col, lang)
  }

  constructor(col = {}, lang = null) {
    this._col = col
    // boolean | object
    // 语言配置信息
    this._lang = lang
    this.reset()
  }

  get lang() {
    if (this._lang) {
      if (typeof this._lang === 'object') {
        return this._lang
      }
      return {
        queryField: this._col.prop,
        updateField: this._col.prop
      }
    }
    return {}
  }

  reset() {
    LangTypeEnum.getValues().forEach(lang => {
      Object.assign(this, { [lang.id]: '' })
    })
  }

  getFirstEmptyLang() {
    return LangTypeEnum.getValues().find(el => !this[el.id] || !this[el.id].trim()) || null
  }

  forEach(callback) {
    LangTypeEnum.getValues().forEach((lang, idx) => {
      callback(lang, this, idx)
    })
    return this
  }

  assignLang(parentObj) {
    const queryField = this._col.lang.queryField || this.lang.queryField || this._col.prop
    const queryFieldValue = parentObj[queryField] || []
    LangTypeEnum.getValues().forEach(lang => {
      const item = queryFieldValue.find(el => el.languageCode === lang.id)
      this[lang.id] = item ? item[this._col.prop] : ''
    })
    return this
  }

  getValue(formData = {}) {
    const updateField = this._col.lang.updateField || this.lang.updateField || this._col.prop
    const result = {
      [this._col.prop]: this[LangTypeEnum.CN.id],
      [updateField]: LangTypeEnum.getValues().map(el => {
        return {
          ...(formData[updateField] ? formData[updateField].find(i => i.languageCode === el.id) : null),
          languageCode: el.id,
          [this._col.prop]: this[el.id]
        }
      })
    }
    // debugger
    // console.log(result)
    return result
  }
}
